<?php
namespace App\Admin\Controllers\Warehousing;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\Supplier;
use App\Models\Inventory\Storage;
use App\Models\Inventory\StoragePurDetail;
use App\Models\Product\ProductClassify;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Encore\Admin\Admin;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class StoragePurDetailController extends AdminController{

    protected $title = '收货入库明细';

    protected function grid()
    {
        $grid = new Grid(new StoragePurDetail());
        $grid->model()->whereHas('storage',function ($query){
            $query->where('type', Storage::TYPE_RECEIVE); //收货入库
        });
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->supplier_name = $item->storage->supplier->name ?? '';
                $item->supplier_amount = numberFormat($item->storage_num * $item->supplier_price);
                $item->amount = numberFormat($item->storage_num * $item->unit_price);
                $item->cuser = User::getUsernameById($item->storage->cuser_id ?? '');
            }
            return $collection;
        });
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('storage_no','入库单');
        $grid->column('order_no','订单号');
        $grid->column('supplier_name','供应商');
        $grid->column('cuser','入库员');
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('skuClassify.title','品类');
        $grid->column('poDetail.order_num','采购数量');
        $grid->column('storage_num','入库数量');
        $grid->column('supplier_price','入库供应商单价');
        $grid->column('supplier_amount','入库供应商金额')->help('入库供应商单价*入库数量');
        $grid->column('unit_price','入库单价');
        $grid->column('unit_price_no_tax','不含税单价')->help('核算月报');
        $grid->column('pack_price','包材单价')->help('核算月报');
        $grid->column('amount','入库金额')->help('入库单价*入库数量');
        $grid->column('created_at','入库时间');

        //汇总TTL
        $total = StoragePurDetail::getStoragePurDetailTotal(Request::input());
        $script = <<<SCRIPT
            $(function($){
                 $(".table>thead:first" ).append(`<tr>
                    <td class="column-storage_no" style="color: red">TTL</td>
                    <td class="column-order_no"></td>
                    <td class="column-supplier_name"></td>
                    <td class="column-cuser"></td>
                    <td class="column-sku-psku_code"></td>
                    <td class="column-sku-psku_cn"></td>
                    <td class="column-sku_classify-season"></td>
                    <td class="column-sku_classify-title"></td>
                    <td class="column-po_detail-order_num" style="color: red">$total->order_num</td>
                    <td class="column-storage_num" style="color: red">$total->storage_num</td>
                    <td class="column-supplier_price" style="color: red">$total->supplier_price</td>
                    <td class="column-supplier_amount" style="color: red">$total->supplier_amount</td>
                    <td class="column-unit_price" style="color: red">$total->unit_price</td>
                    <td class="column-unit_price_no_tax" style="color: red">$total->unit_price_no_tax</td>
                    <td class="column-pack_price" style="color: red">$total->pack_price</td>
                    <td class="column-amount" style="color: red">$total->amount</td>
                    <td class="column-created_at"></td>
                 </tr>`);
            });
SCRIPT;
        Admin::script($script);

        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('warehousing/storage-pur-detail-download'));
        });
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('storage_no','入库单');
                $filter->equal('order_no','订单号');
                $filter->equal('storage.supplier_id','供应商')->select(Supplier::options());
            });
            $filter->column(1/2, function ($filter){
                $filter->between('created_at', '入库时间')->datetime();
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = StoragePurDetail::query()
            ->whereHas('storage',function ($query){
                $query->where('type', Storage::TYPE_RECEIVE); //收货入库
            })->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if($key == 'storage'){
                $query->whereHas('storage', function ($query) use($_filter){
                    $query->where('supplier_id', $_filter['supplier_id']);
                });
            }
            if($key == 'created_at'){
                if(isset($_filter['start'])&&$_filter['start']){
                    $query->where('created_at','>=',$_filter['start']);
                }
                if(isset($_filter['end'])&&$_filter['end']){
                    $query->where('created_at','<=',$_filter['end']);
                }
            }
            if(in_array($key,['storage_no','order_no'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['入库单','订单号','供应商','入库员','SKU','产品名称','季节性','品类',
            '采购数量','入库数量','入库供应商单价','入库供应商金额','入库单价','包材单价','不含税单价','入库金额','入库时间'];
        RExcel::exportCsv('收货入库明细',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->storage->cuser_id ?: 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $temp = [
                $model->storage_no,
                $model->order_no ?: '',
                $model->storage->supplier->name ?? '',
                $seller[$sellerId],
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                ProductClassify::$_season[$model->skuClassify->season ?? 3],
                $model->skuClassify->title ?? '',
                $model->poDetail->order_num ?? 0,
                $model->storage_num ?: 0,
                $model->supplier_price ?: 0,
                numberFormat(round(($model->storage_num ?: 0) * ($model->supplier_price ?: 0),3)),
                $model->unit_price ?: 0,
                $model->pack_price ?: 0,
                $model->unit_price_no_tax ?: 0,
                numberFormat(round(($model->storage_num ?: 0) * ($model->unit_price ?: 0),3)),
                $model->created_at,
            ];
            yield $temp;
        }
    }
}
